package logic

import (
	"context"
	"github.com/jinzhu/copier"
	"xialou_platform/app/requestx"

	"xialou_platform/services/agent/rpc/agentClient"
	"xialou_platform/services/agent/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AgentChildLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAgentChildLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AgentChildLogic {
	return &AgentChildLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// AgentChild 获取代理商下面的销客列表
func (l *AgentChildLogic) AgentChild(in *agentClient.AgentChildReq) (*agentClient.AgentChildListResp, error) {
	// todo: add your logic here and delete this line
	count := l.svcCtx.AgentModel.FindListCountByParentId(l.ctx, in.ParentUid)
	data := make([]*agentClient.AgentParam, 0)
	if count > 0 {
		list, err := l.svcCtx.AgentModel.FindListByParentId(l.ctx, &requestx.ListReq{
			Page:     in.Page,
			PageSize: in.PageSize,
		}, in.ParentUid)
		if err != nil {
			return nil, err
		}
		for _, agent := range list {
			var v agentClient.AgentParam
			err := copier.Copy(&v, agent)
			if err != nil {
				continue
			}
			v.CreateTime = agent.CreateTime.Unix()
			v.UpdateTime = agent.UpdateTime.Unix()
			v.SubCount = l.svcCtx.AgentModel.FindListCountByParentId(l.ctx, agent.Id)
			if err != nil {
				return nil, err
			}
			data = append(data, &v)
		}
	}
	return &agentClient.AgentChildListResp{
		Total: count,
		List:  data,
	}, nil
}
